import pymysql


class Cpymysql():
    def __init__(self):
        self.conn = pymysql.connect(host='www.zdiml.xyz',
                                    port=3306,
                                    user='mqtt',
                                    password='zucc511',
                                    database='mqtt')
        self.cur = self.conn.cursor()

    # 执行任意 sql 语句
    def change_db(self, sql):
        # 执行sql语句
        self.cur.execute(sql)
        # 提交事务
        self.conn.commit()

    # 查询
    def query_db(self, sql, mod='all'):
        # 执行sql语句
        self.cur.execute(sql)
        # 获取数据
        if mod == 'all':
            result01 = self.cur.fetchall()
        elif mod == 'one':
            result01 = self.cur.fetchone()
        elif mod == 'many':
            result01 = self.cur.fetchmany()
        else:
            result01 = "Illegal"
        return result01

    # 断开连接
    def __del__(self):
        self.cur.close()
        self.conn.close()


conn = Cpymysql()
sql = "insert into IOT_ZYY(Topic, Qos, Payload) values('%s', %d, '%s')" % (
    'topic', 1, 'payload')
print(conn.change_db(sql))
